'use strict';

const Service = require('egg').Service;
class ShopService extends Service {
  async getShopList() {
    const { ctx, app } = this;
    const { pageIndex, pageSize, keyword } = ctx.query;
    let sql = `select * from shops where 1=1 `
    let totalSql = `select count(id) as total from shops where 1=1 `
    // 关键词查询
    if (keyword) {
      sql += `and title like "%${keyword}%" `
      totalSql += `and title like "%${keyword}%" `
    }
    // 分页
    if (pageIndex && pageSize) {
      sql += `limit ${(pageIndex - 1) * pageSize},${pageSize}`
    }
    const res = await app.mysql.query(sql)
    const [{ total }] = await app.mysql.query(totalSql)

    return {
      list: res,
      total: total
    };
  }
  async getShopDetail() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    const res = await app.mysql.get('shops', { id })
    return res;
  }
  // 加入购物车
  async addToCart() {
    const { ctx, app } = this;
    const { user_id, shop_id } = ctx.request.body;
    // 是更新count 还是添加数据
    const isHave = await app.mysql.get('carts', { user_id, shop_id })
    let res;
    if (isHave) {
      // 更新
      res = await app.mysql.update('carts', { id: isHave.id, count: isHave.count + 1 })
    } else {
      // 第一次加入购物车
      res = await app.mysql.insert('carts', { user_id, shop_id })
    }
    return res;
  }
  // 获取购物车列表
  async getCartList() {
    const { ctx, app } = this;
    const { user_id } = ctx.query;
    const res = await app.mysql.select('carts', {
      where: { user_id }
    })
    // 多表联查
    const allP = res.map((item) => {
      return app.mysql.get('shops', { id: item.shop_id })
    })
    // Promise.all 接收一个由promise组成的数组  全部成功则成功
    const list = await Promise.all(allP)
    // 合并商品数据和购物车数据
    const newList = list.map((item, index) => {
      return {
        ...item,
        ...res[index]
      }
    })
    return newList;
  }
  // 修改购物车商品数量
  async setCartCount() {
    const { ctx, app } = this;
    const { id, count } = ctx.request.body;
    // carts 更新要通过 唯一的主键  id
    const res = await app.mysql.update('carts', {
      id, count
    })
    return res;
  }
  // 删除购物车
  async delCartById() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    // carts 更新要通过 唯一的主键  id
    const res = await app.mysql.delete('carts', {
      id
    })
    return res;
  }
}

module.exports = ShopService;
